package com.ruoyi.web.controller.gzh;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.vo.CityVo;
import org.json.JSONArray;
import org.json.JSONStringer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhiyuan
 * @Date 2023/10/29 13:36
 */
@RestController
public class WeatherController {

    @Autowired
    private RedisCache redisCache;

    @Value("${zhiyuan.WeatherKey}")
    private String WeatherKey;

    /**
     * 根据城市名，查询天气情况
     * @param vo
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/getWeatherByLocalIP")
    public AjaxResult getWeather(CityVo vo) throws UnsupportedEncodingException {
        AjaxResult result = AjaxResult.success();
        if (StringUtils.isEmpty(vo.getCity())){
            String localCityName = GetLocationAndIP.getLocalCityName();
            vo.setCity(localCityName);
        }
        //先查缓存，取数据
        String key = CacheConstants.CITY_NAME_KEY + vo.getCity();
        String cacheString = redisCache.getCacheString(key);
        if (StringUtils.isNotEmpty(cacheString)){
             result.put("msg", cacheString);
            return result;
        }
        //调用天气API
        String encodeCity = URLEncoder.encode(vo.getCity(), "UTF-8");
         String url = "http://apis.juhe.cn/simpleWeather/query?city=" + encodeCity + "&key="+WeatherKey;
        String weatherInfo = HttpUtils.sendGet(url);
        result.put("msg", weatherInfo);
        Integer tomorrowTimestamp = redisCache.getTomorrowTimestamp();
        //从缓存存数据
        redisCache.setCacheObject(key,weatherInfo,tomorrowTimestamp, TimeUnit.SECONDS);
        return result;
    }

    /**
     * 得到本地城市数据
     * @return
     */
    @GetMapping("/getLocalCityName")
    public AjaxResult getLocalCityName() {
        AjaxResult result = AjaxResult.success();
        String localCityName = GetLocationAndIP.getLocalCityName();
        result.put("cityName",localCityName);
        return result;
    }
}
